<template>
  <div class="admin-leave-management">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>学生请假申请管理</span>
          <div class="header-controls">
            <el-input
              v-model="searchQuery"
              placeholder="搜索学生姓名/学号"
              style="width: 250px; margin-right: 10px"
              clearable
              @input="handleSearch"
            >
              <template #prefix>
                <el-icon><search /></el-icon>
              </template>
            </el-input>
            <el-select v-model="statusFilter" placeholder="状态筛选" style="width: 120px" @change="handleSearch">
              <el-option label="全部" value=""></el-option>
              <el-option label="待审批" value="PENDING"></el-option>
              <el-option label="已批准" value="APPROVED"></el-option>
              <el-option label="已拒绝" value="REJECTED"></el-option>
            </el-select>
            <el-button type="primary" size="small" @click="fetchLeaveApplications" style="margin-left: 10px;">刷新</el-button>
          </div>
        </div>
      </template>
      
      <el-table :data="filteredApplications" style="width: 100%">
        <el-table-column prop="studentId" label="学号" width="120" />
        <el-table-column prop="studentName" label="姓名" width="120" />
        <el-table-column prop="application.leaveType" label="请假类型" width="100" />
        <el-table-column prop="application.leaveReason" label="请假原因" />
        <el-table-column label="开始时间" width="180">
          <template #default="scope">
            {{ formatDate(scope.row.application.startDate) }}
          </template>
        </el-table-column>
        <el-table-column label="结束时间" width="180">
          <template #default="scope">
            {{ formatDate(scope.row.application.endDate) }}
          </template>
        </el-table-column>
        <el-table-column prop="affectedCourseNames" label="涉及课程" width="200">
          <template #default="scope">
            <el-tooltip :content="scope.row.affectedCourseNames" placement="top" :show-after="500">
              <span>{{ scope.row.affectedCourseNames }}</span>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column prop="application.status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.application.status)">
              {{ getStatusText(scope.row.application.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="拒绝原因" width="150">
          <template #default="scope">
            <span v-if="scope.row.application.status === 'REJECTED' && scope.row.application.rejectReason">
              <el-tooltip :content="scope.row.application.rejectReason" placement="top" :show-after="500">
                <el-button type="text">查看原因</el-button>
              </el-tooltip>
            </span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <div v-if="scope.row.application.status === 'PENDING'">
              <el-button 
                type="success" 
                size="small" 
                @click="approveLeave(scope.row.application.id, true)"
              >
                批准
              </el-button>
              <el-button 
                type="danger" 
                size="small" 
                @click="showRejectDialog(scope.row.application.id)"
              >
                拒绝
              </el-button>
            </div>
            <span v-else>-</span>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container">
        <el-pagination
          v-if="filteredApplications.length > 0"
          :current-page="currentPage"
          :page-sizes="[10, 20, 30, 50]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalApplications"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        ></el-pagination>
      </div>
    </el-card>
    
    <!-- 拒绝请假申请对话框 -->
    <el-dialog v-model="rejectDialogVisible" title="拒绝请假申请" width="500px">
      <el-form :model="rejectForm">
        <el-form-item label="拒绝原因" label-width="100px">
          <el-input 
            v-model="rejectForm.reason" 
            type="textarea" 
            :rows="4"
            placeholder="请输入拒绝原因"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="rejectDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="approveLeave(rejectForm.applicationId, false)">
            确认拒绝
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, onMounted, onUnmounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import axios from 'axios'

export default {
  name: 'AdminLeaveManagement',
  components: {
    Search
  },
  setup() {
    const leaveApplications = ref([])
    const currentPage = ref(1)
    const pageSize = ref(10)
    const searchQuery = ref('')
    const statusFilter = ref('')
    const rejectDialogVisible = ref(false)
    const rejectForm = ref({
      applicationId: null,
      reason: ''
    })
    
    // 过滤后的申请列表
    const filteredApplications = computed(() => {
      let filtered = [...leaveApplications.value]
      
      // 状态筛选
      if (statusFilter.value) {
        filtered = filtered.filter(item => 
          item.application.status === statusFilter.value
        )
      }
      
      // 搜索筛选
      if (searchQuery.value) {
        const query = searchQuery.value.toLowerCase()
        filtered = filtered.filter(item => 
          (item.studentId && item.studentId.toLowerCase().includes(query)) ||
          (item.studentName && item.studentName.toLowerCase().includes(query))
        )
      }
      
      return filtered
    })
    
    // 总申请数量
    const totalApplications = computed(() => {
      return filteredApplications.value.length
    })
    
    // 获取所有请假申请
    const fetchLeaveApplications = async () => {
      try {
        console.log('开始获取请假申请，请求路径: /api/admin/leave-applications');
        // 尝试使用axios直接调用
        const response = await axios.get('/api/admin/leave-applications');
        console.log('获取请假申请成功:', response);
        leaveApplications.value = response.data;
        console.log('请假申请数据:', leaveApplications.value);
      } catch (error) {
        console.error('获取请假申请失败:', error);
        console.error('错误详情:', error.message);
        if (error.response) {
          console.error('错误响应状态:', error.response.status);
          console.error('错误响应数据:', error.response.data);
        } else if (error.request) {
          console.error('没有收到响应，请求详情:', error.request);
        }
        ElMessage.error(`获取请假申请失败: ${error.message}`);
      }
    }
    
    // 显示拒绝对话框
    const showRejectDialog = (applicationId) => {
      rejectForm.value.applicationId = applicationId
      rejectForm.value.reason = ''
      rejectDialogVisible.value = true
    }
    
    // 审批请假申请
    const approveLeave = async (applicationId, approved) => {
      try {
        // 如果是拒绝，需要添加拒绝原因
        if (!approved) {
          if (!rejectForm.value.reason) {
            ElMessage.warning('请输入拒绝原因')
            return
          }
          rejectDialogVisible.value = false
        } else {
          // 如果是批准，弹出确认框
          try {
            await ElMessageBox.confirm('确认批准该请假申请?', '确认', {
              confirmButtonText: '确认',
              cancelButtonText: '取消',
              type: 'info'
            })
          } catch (e) {
            return // 用户取消
          }
        }
        
        // 查找当前申请的完整信息
        const currentApplication = leaveApplications.value.find(item => 
          item.application && String(item.application.id) === String(applicationId)
        );
        
        console.log('当前申请完整信息:', currentApplication);
        
        if (!currentApplication) {
          ElMessage.error('找不到对应的请假申请信息');
          return;
        }
        
        // 使用当前申请的实际ID，确保以字符串形式传递
        const actualId = String(currentApplication.application.id);
        console.log('使用实际ID:', actualId);
        
        const requestData = {
          approved: approved,
          rejectReason: !approved ? rejectForm.value.reason : null
        }
        
        console.log('发送请假审批请求:', {
          url: `/api/admin/leave-applications/${actualId}/approve`,
          data: requestData
        });

        // 使用axios发送请求
        const response = await axios({
          method: 'post',
          url: `/api/admin/leave-applications/${actualId}/approve`,
          data: requestData,
          headers: {
            'Content-Type': 'application/json'
          }
        });
        
        console.log('请假审批完整响应:', response);
        
        if (response.status === 200) {
          if (response.data && response.data.success) {
            ElMessage.success(approved ? '请假申请已批准' : '请假申请已拒绝');
            await fetchLeaveApplications(); // 重新加载数据
            
            // 通知待办事项状态更新
            try {
              // 使用全局事件总线或直接更新待办事项列表
              await axios.get('/api/admin/todo');
              // 触发自定义事件通知其他组件更新待办事项
              window.dispatchEvent(new CustomEvent('check-admin-todos'));
            } catch (error) {
              console.error('更新待办事项状态失败:', error);
            }
          } else {
            const errorMsg = response.data && response.data.message ? response.data.message : '操作失败';
            console.error('操作失败 (后端返回):', errorMsg, response.data);
            ElMessage.error(errorMsg);
          }
        } else {
          console.error('HTTP错误状态码:', response.status);
          ElMessage.error(`请求错误: ${response.status}`);
        }
      } catch (error) {
        console.error('审批请假申请失败:', error);
        console.error('错误详情:', error.message);
        
        if (error.response) {
          console.error('错误响应状态:', error.response.status);
          console.error('错误响应数据:', error.response.data);
          ElMessage.error(`审批请假申请失败: ${error.response.data?.message || error.message}`);
        } else if (error.request) {
          console.error('没有收到响应，请求详情:', error.request);
          ElMessage.error('审批请假申请失败，未收到服务器响应');
        } else {
          ElMessage.error(`审批请假申请失败: ${error.message}`);
        }
      }
    }
    
    const handleSearch = () => {
      currentPage.value = 1
    }
    
    const handleSizeChange = (val) => {
      pageSize.value = val
      currentPage.value = 1
    }
    
    const handleCurrentChange = (val) => {
      currentPage.value = val
    }
    
    const getStatusType = (status) => {
      const statusMap = {
        'PENDING': 'warning',
        'APPROVED': 'success',
        'REJECTED': 'danger'
      }
      return statusMap[status] || 'info'
    }
    
    const getStatusText = (status) => {
      const statusMap = {
        'PENDING': '待审批',
        'APPROVED': '已批准',
        'REJECTED': '已拒绝'
      }
      return statusMap[status] || '未知'
    }
    
    const formatDate = (dateStr) => {
      if (!dateStr) return '';
      const d = new Date(dateStr);
      return `${d.getFullYear()}/${d.getMonth()+1}/${d.getDate()} ${d.getHours().toString().padStart(2,'0')}:${d.getMinutes().toString().padStart(2,'0')}`;
    }
    
    let timer = null
    onMounted(() => {
      fetchLeaveApplications()
      // 定时轮询刷新
      timer = setInterval(() => {
        fetchLeaveApplications()
      }, 5000)
    })
    onUnmounted(() => {
      if (timer) clearInterval(timer)
    })
    
    return {
      leaveApplications,
      filteredApplications,
      currentPage,
      pageSize,
      totalApplications,
      searchQuery,
      statusFilter,
      rejectDialogVisible,
      rejectForm,
      approveLeave,
      showRejectDialog,
      handleSearch,
      handleSizeChange,
      handleCurrentChange,
      getStatusType,
      getStatusText,
      fetchLeaveApplications,
      formatDate
    }
  }
}
</script>

<style scoped>
.admin-leave-management {
  margin: 20px 0;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-controls {
  display: flex;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style> 